/****************************************************************************
 *
 * Copyright (C) 2003-2010 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.netflow;

import java.sql.Timestamp;
import java.util.StringTokenizer;

import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecordField;
import nfse.gui.server.GUIRecordFactory;
import nfse.gui.server.RecordBuilderUtil;

public class NetflowRecordFactory extends GUIRecordFactory<NetflowRecord> {

    public NetflowRecordFactory() {
        builder = new RecordBuilderUtil();
        builder.addColumn(null, "ID", RecordBuilderUtil.BIGINT);
        RecordBuilderUtil.SQLField field = builder.addColumn("Start TS", "startts", RecordBuilderUtil.TIMESTAMP);
        field = builder.addColumn("End TS", "endts", RecordBuilderUtil.TIMESTAMP);
        field = builder.addColumn("Src IP", "srcip", RecordBuilderUtil.INET);
        field = builder.addColumn("Src Port", "srcport", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PORT);
        field = builder.addColumn("Dst IP", "dstip", RecordBuilderUtil.INET);
        field = builder.addColumn("Dst Port", "dstport", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PORT);
        field = builder.addColumn("Bytes", "bytes", RecordBuilderUtil.BIGINT);
        field = builder.addColumn("Pkts", "pkts", RecordBuilderUtil.BIGINT);
        field = builder.addColumn("Protocol", "protocol", RecordBuilderUtil.INTEGER);
        field.setSubtype(FlexRecordField.SUB_TYPE_PROTOCOL);
    }

    @Override
    protected void setValues(NetflowRecord record, int id) {
        int idx = -1;
        builder.setFieldValue(++idx, "" + id);
        builder.setFieldValue(++idx, "" + record.getStartTS());
        builder.setFieldValue(++idx, "" + record.getEndTS());
        builder.setFieldValue(++idx, record.getSrcAddr());
        builder.setFieldValue(++idx, "" + record.srcPort);
        builder.setFieldValue(++idx, record.dstAddr);
        builder.setFieldValue(++idx, "" + record.dstPort);
        builder.setFieldValue(++idx, "" + record.srcBytes);
        builder.setFieldValue(++idx, "" + record.srcPkts);
        builder.setFieldValue(++idx, "" + record.proto);

    }

    /***************************************************************************
     * Parse a NetFlow record into a NetflowRecord data structure.
     * 
     * @param line
     *            The NetFlow record
     * @return The parsed NetFlowRecord
     */
    @Override
    public NetFSERecord generate(String line, int sensor) throws Exception {

        NetflowRecord l = new NetflowRecord();
        l.setTypeName(typeName);
        l.setTypeID(typeID);
        l.version = 1;
        l.setInitialString(line);
        l.setSensorID(sensor);
        String[] tokens = null;
        StringTokenizer st = new StringTokenizer(line);
        tokens = new String[st.countTokens()];
        for (int i = 0; i < tokens.length; i++)
            tokens[i] = st.nextToken();
        // if (tokens.length != NUM_FIELDS) {
        // throw(new Exception("Invalid number of tokens: " +
        // tokens.length));
        // }

        Timestamp ts = Timestamp.valueOf(tokens[0] + " " + tokens[1]);
        l.setStartTS(ts);

        boolean testing = true;
        if (testing) {
            Timestamp startTS = new Timestamp(System.currentTimeMillis());
            l.setStartTS(startTS); // DELETE
            String[] temp = startTS.toString().split(" ");
            tokens[0] = temp[0];
            tokens[1] = temp[1];
            line = "";
            for (int i = 0; i < tokens.length; i++) 
                line += tokens[i] + " ";
            l.setInitialString(line.trim());
        }

        long duration = (long) (Float.parseFloat(tokens[2]) * 1000);
        l.setEndTS(new Timestamp(ts.getTime() + duration));

        l.proto = NetFSEUtil.getProtocol(tokens[3]);

        String[] src = tokens[4].split(":");
        l.setSrcIP(NetFSEUtil.convertIPtoLong(src[0]));
        l.srcPort = (int) Float.parseFloat(src[1]);

        String[] dst = tokens[6].split(":");
        l.setDstIP(NetFSEUtil.convertIPtoLong(dst[0]));
        l.dstPort = (int) Float.parseFloat(dst[1]);

        l.tcpFlags = tokens[7];

        l.tos = Integer.parseInt(tokens[8]);
        l.srcPkts = Long.parseLong(tokens[9]);

        try {
            l.srcBytes = Long.parseLong(tokens[10]);
            l.numFlows = Integer.parseInt(tokens[11]);
        } catch (NumberFormatException nme) {
            long incr = 1;
            if (tokens[11].equals("M")) {
                incr = 1000000;
            } else if (tokens[11].equals("T")) {
                incr = 1000;
            } else if (tokens[11].equals("B")) {
                incr = 1000000000;
            }
            l.srcBytes = (long) (Float.parseFloat(tokens[10]) * incr);

            l.numFlows = Integer.parseInt(tokens[12]);
        }
        
        return l; // The record was successfully parsed, return it

    }

    @Override
    public NetFSERecord generate() {
        return new NetflowRecord();
    }

}
